<template>
  <div class="app-container">
    <!-- 标题 -->
    <h2>序列号管理</h2>
    <h3>打印机序列号</h3>

    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="序列号">
        <el-input v-model="queryParams.sn" placeholder="请输入序列号" clearable />
        <!--  sn 序列号-->
      </el-form-item>
      <el-form-item label="打印机类型">
        <el-select v-model="queryParams.printertype" placeholder="请选择打印机类型" clearable>
          <el-option label="便携式打印机" value="1" />
          <el-option label="高速打印机" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="使用情况">
        <el-select v-model="queryParams.printstatus" placeholder="请选择使用情况" clearable>
          <el-option label="已使用" :value="1" />
          <el-option label="未使用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="success" @click="handleExport">导出</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button  type="success" @click="handleImport">导入</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      ref="table"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="sn" label="序列号" />
      <el-table-column prop="registerTime" label="创建时间"/>

      <el-table-column prop="printertype" label="类型">
        <template #default="{ row }">
          <el-tag :type="parseInt(row.printertype) === 1 ? 'success' : 'info'">{{ parseInt(row.printertype) === 1 ? '便携式打印机' : '高速打印机' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="printstatus" label="使用情况">
        <template #default="{ row }">
          <el-tag :type="parseInt(row.printstatus) === 1 ? 'success' : 'warning'">{{ parseInt(row.printstatus) === 1 ? '已使用' : '未使用' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px;"
    />

    <!-- 批量操作提示 -->
    <div v-if="selectedRows.length > 0" class="batch-operation">
      已选择 {{ selectedRows.length }} 条
      <el-button size="small" @click="clearSelection">清空</el-button>
    </div>
    <!-- 新增弹窗组件 -->
    <el-dialog title="新增" :visible.sync="addDialogVisible" width="500px">
      <el-form :model="addForm" label-width="100px" :rules="addRules" ref="addForm">
        <!-- 序列号输入框 -->
        <el-form-item label="序列号：" prop="sn">
          <el-input v-model="addForm.sn" placeholder="请输入序列号" />
        </el-form-item>

        <!-- 打印机类型选择框 -->
        <el-form-item label="类型：" prop="printertype">
          <el-select v-model="addForm.printertype" placeholder="请选择打印机类型">
            <el-option label="便携式打印机" :value="1" />
            <el-option label="高速打印机" :value="0" />
          </el-select>
        </el-form-item>

        <!-- 使用状态按钮组 -->
        <el-form-item label="使用状态：" prop="printstatus">
          <el-radio-group v-model="addForm.printstatus">
            <el-radio-button label="0">未使用</el-radio-button>
            <el-radio-button label="1">已使用</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- 创建时间字段（只读） -->
        <el-form-item label="创建时间：">
          <el-input v-model="addForm.registerTime" disabled />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="submitAddData">确 定</el-button>
      </div>
    </el-dialog>
<!--导入弹出-->
    <el-dialog title="导入打印机序列号" :visible.sync="importDialogVisible" width="500px">
      <el-form label-width="100px">
        <el-form-item label="选择文件">
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept=".xlsx, .xls"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">
              <div>只能上传xlsx、xls格式文件</div>
              <div>请按照模板格式上传，确保数据正确</div>
              <el-button size="small" type="text" @click="downloadTemplate">下载模板</el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelImport">取 消</el-button>
        <el-button
          type="primary"
          @click="submitImport"
          :loading="importLoading"
          :disabled="fileList.length === 0"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editObjects" label-width="100px" :rules="editRules" ref="editObjects">
        <!-- 序列号字段（只读） -->
        <el-form-item label="序列号" prop="sn">
          <el-input v-model="editObjects.sn" placeholder="请输入序列号" disabled />
        </el-form-item>

        <!-- 创建时间字段（只读） -->
        <el-form-item label="创建时间" prop="registerTime">
          <el-input v-model="editObjects.registerTime" placeholder="请输入创建时间" disabled />
        </el-form-item>

        <el-form-item label="打印机类型" prop="printertype">
          <el-select v-model="editObjects.printertype" placeholder="请选择打印机类型">
            <el-option label="便携式打印机" :value="1" />
            <el-option label="高速打印机" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="打印机状态" prop="printstatus">
          <el-select v-model="editObjects.printstatus" placeholder="请选择打印机状态">
            <el-option label="已使用" :value="1" />
            <el-option label="未使用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import * as http from "http";
import {addPrinterSn, deletePrinterSn, listsnmanagement, updatePrinterSn,importPrinterSn} from "../../../../api/printer/sn/printersn";
import {parseTime} from "@/utils/ruoyi";
export default {
  name: "Printer",
  dicts:['printer_printertype','printer_printstatus'],
  computed: {
    http() {
      return http
    }
  },
  data() {
    return {
      queryParams: {
        sn: "",
        printertype: undefined,
        printstatus: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 导出
      importDialogVisible: false,
      fileList: [],
      importLoading: false,
      // 新增
      addDialogVisible: false,
      addForm: {
        sn: '',
        printertype: 0,
        printstatus: 0,
        registerTime: '' // 添加创建时间字段
      },
      addRules: {
        sn: [
          { required: true, message: '打印机序列号不能为空', trigger: 'blur' }
        ],
        printertype: [
          { required: true, message: '请选择打印机类型', trigger: 'change' }
        ],
        printstatus: [
          { required: true, message: '请选择使用状态', trigger: 'change' }
        ]
      },


      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selectedRows: [],
      // 编辑弹窗相关数据
      editDialogVisible: false,
      editObjects: {
        id: null,
        sn: '',
        registerTime: '',
        printertype: 0,
        printstatus: 1
      },
      editRules: {
        printertype: [
          {required: true, message: '请选择打印机类型', trigger: 'change'}
        ],
        printstatus: [
          {required: true, message: '请选择打印机状态', trigger: 'change'}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    handleExport() {
      // 如果有选中的行，则只导出选中的行
      if (this.selectedRows && this.selectedRows.length > 0) {
        // 可以选择导出选中行的ID或其他标识
        const selectedIds = this.selectedRows.map(row => row.id).join(',');
        this.download('snmanagement/printerSn/export', {
          ...this.queryParams,
          ids: selectedIds  // 传递选中行的ID
        }, `sn_selected_${new Date().getTime()}.xlsx`)
      } else {
        // 没有选中行则导出当前查询结果
        this.download('snmanagement/printerSn/export', {
          ...this.queryParams
        }, `sn_${new Date().getTime()}.xlsx`)
      }
    },

// 删除
    handleDelete(row) {
      this.$confirm('确认要删除该打印机序列号信息吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 传递 row.id 而不是 row
        return deletePrinterSn(row.id)
      }).then(() => {
        this.getList() // 删除成功后重新获取列表
        this.$message.success('删除成功')
      }).catch((error) => {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      })
    },


    submitData() {
      updatePrinterSn(this.editObjects).then(response => {
        // 刷新表格数据
        this.getList()
        this.$modal.msgSuccess(response.msg);
        // 关闭弹窗
        this.editDialogVisible = false;
      })
    },
// 新增
    handleAdd() {
      this.addForm = {
        sn: '',
        printertype: 0,
        printstatus: '0',
        registerTime: new Date().toLocaleString() // 自动生成本地时间
      };
      this.addDialogVisible = true;
    },


    // 提交新增数据
    // 在 submitAddData 方法中修改
    submitAddData() {
      // 首先检查序列号是否已存在
      this.$refs.addForm.validate(valid => {
        if (valid) {
          // 查询是否存在相同序列号
          listsnmanagement({ sn: this.addForm.sn }).then(response => {
            if (response.rows && response.rows.length > 0) {
              this.$message.error('该序列号已存在，请使用其他序列号');
              return;
            }

            // 格式化时间字段
            const date = new Date();
            this.addForm.registerTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;

            addPrinterSn(this.addForm).then(response => {
              this.$message.success('添加成功');
              this.addDialogVisible = false;
              this.getList();
            }).catch(() => {
              this.$message.error('添加失败');
            });
          });
        }
      });
    },


    // 处理导入按钮点击
    handleImport() {
      this.importDialogVisible = true;
      this.fileList = [];
    },

    // 处理文件选择变化
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-1); // 只保留最后一个文件
    },

    // 下载导入模板
    downloadTemplate() {
      this.download('snmanagement/printerSn/importTemplate', {}, `打印机序列号导入模板.xlsx`);
    },

    // 提交导入
    submitImport() {
      if (this.fileList.length === 0) {
        this.$message.warning('请选择要导入的文件');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.fileList[0].raw);
      formData.append('updateSupport', false); // 添加是否更新已存在数据的参数

      this.importLoading = true;

      importPrinterSn(formData).then(response => {
        this.importLoading = false;
        this.importDialogVisible = false;
        this.$message.success(response.msg || '导入成功');
        this.getList(); // 刷新列表
      }).catch(error => {
        this.importLoading = false;
        // this.$message.error('导入失败: ' + (error.msg || '未知错误'));
      });
    },

    // 取消导入
    cancelImport() {
      this.importDialogVisible = false;
      this.fileList = [];
    },


    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listsnmanagement(this.queryParams).then(response => {
        // 确保所有状态字段都是数字类型
        const rows = response.rows.map(item => {
          return {
            ...item,
            printertype: parseInt(item.printertype),
            printstatus: parseInt(item.printstatus),
          };
        });
        this.tableData = rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetForm() {
      this.queryParams = {
        sn: "",
        printertype: undefined,
        printstatus: undefined,
        pageNum: 1,
        pageSize: 10
      };
      this.getList();
    },

    handleEdit(row) {
      console.log("编辑", row);
      // 设置编辑表单数据
      this.editObjects = {
        id: row.id,
        sn: row.sn,
        registerTime: row.registerTime,
        printertype: parseInt(row.printertype),
        printstatus: parseInt(row.printstatus)
      };
      // 显示编辑弹窗
      this.editDialogVisible = true;
    },

    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    clearSelection() {
      this.$refs.table.clearSelection();
      this.selectedRows = [];
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },



  }
};
</script>

<style scoped lang="scss">
.batch-operation {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  margin-left: 10px;
}
</style>
